package gcpool

import (
	"errors"
	"net/http"
	"dhfshop/utils/response"
	"github.com/astaxie/beego"
	"github.com/gorilla/websocket"
)

var GO_CONN_POOL *Pool

func WebsocketHandler(w http.ResponseWriter, r *http.Request, id string) (int, error) {
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		return 4007, errors.New(response.LangConf.Get("4007").MustString())
	} else if err != nil {
		return 4008, errors.New(response.LangConf.Get("4008").MustString())
	}
	GO_CONN_POOL.GetConn("default").Add(id, ws)    //保存连接
	defer GO_CONN_POOL.GetConn("default").Del(id)  //退出后,移除节点
	for {
		beego.Debug("websocket enter loop")
		_, message, err := ws.ReadMessage()
		if err != nil {
			break
		}
		beego.Debug("message:", string(message))
		GO_CONN_POOL.GetStream("default").Add(id, message)
	}
	return 0, err
}

